package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.pg.domain.Attachment;
import com.ruoyi.pg.service.IAttachmentService;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysPostService postService;

    @Resource
    private IAttachmentService attachmentService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        /*//获取当前用户角色
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        String roleKey = sysUser.getRoles().get(0).getRoleKey();
        if(!"admin".equals(roleKey)){
            user.setRoleKey(roleKey);
        }*/
        startPage();
        List<SysUser> list = this.userService.selectUserList(user);
        /*for (SysUser user1 : list){
            Attachment attachment = this.attachmentService.selectAttachmentByTeacherId(user1.getUserId());
            if(attachment != null){
                user1.setHasAttachment(true);
            }else{
                user1.setHasAttachment(false);
            }
        }*/
        //System.out.println("this.getDataTable(list).getTotal() = " + this.getDataTable(list).getTotal());
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser2(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        this.attachmentService.deleteAttachmentByTeacherIds(userIds);
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping("/uploadPdf")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files, @RequestParam(value = "deptId") Long deptId) {
        AjaxResult result = AjaxResult.success();
        List<String> successFiles = new ArrayList<>();
        List<String> failFiles = new ArrayList<>();
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();

            // 1. 获取完整指标点路径（从根节点开始）
            SysDept dept = this.deptService.selectDeptById(deptId);
            //附件保存路径
            String fullPdfPath = "赤峰学院/专任教师/" + dept.getDeptName();

            // 2. 构建存储路径（包含根节点"赤峰学院"）
            String storagePath = RuoYiConfig.getUploadPath() + "/" + fullPdfPath;

            // 3. 创建目录（如果不存在）
            File dir = new File(storagePath);
            if (!dir.exists() && !dir.mkdirs()) {
                throw new IOException("目录创建失败: " + storagePath);
            }

            // 4. 处理每个文件
            for (MultipartFile file : files) {
                if (file.isEmpty()) continue;

                //016杜致燕（护理学院兼任教师）.pdf, 0789赵慧敏（教师教育学院）.pdf
                String originalFilename = file.getOriginalFilename();
                System.out.println("originalFilename ======================== " + originalFilename);
                //杜致燕,赵慧敏
                String nickName = this.extractName(originalFilename);
                System.out.println("nickName ==================================== " + nickName);
                String filePath = fullPdfPath + "/" + originalFilename;
                String savePath = storagePath + "/" + originalFilename;
                //016
                String code4 = originalFilename.substring(0, 3);

                // 保存到数据库
                // 通过nickName和deptId在user表中查询，如果能找到一条记录，则需要获取该条记录的userId，将之与附件表中的teacherId对应
                // 若user为空，说明没有改教师，则不能上传资料
                // 若user不为空，说明该教师存在:
                //             如果 attach 为空，说明该教师还没有上传个人附件，则直接上传附件
                //             如果 attach 不为空，说明该教师已经上传个人附件，需要先删除该附件，再上传新的附件
                //SysUser user = userService.selectUserByNickNameAndDeptId(nickName, deptId);
                SysUser user = userService.selectUserByUserNameAndNickNameAndDeptId(code4, nickName, deptId);

                if(user!=null){//
                    user.setUserName(code4);
                    this.userService.updateUser(user);
                    System.out.println("user ======================================================== " + user.getUserId() +":" +user.getNickName());
                    Attachment attach = this.attachmentService.selectAttachmentByTeacherId(user.getUserId());
                    if(attach == null) {
                        Attachment attachment = new Attachment();
                        attachment.setTeacherId(user.getUserId());
                        attachment.setFileName(originalFilename);
                        attachment.setFilePath(filePath);
                        attachment.setFileSize(file.getSize());
                        attachment.setFileType(this.getFileExtension(originalFilename));
                        attachment.setCreateBy(SecurityUtils.getUsername());
                        attachment.setCreateTime(DateUtils.getNowDate());
                        this.attachmentService.insertAttachment(attachment);
                        successFiles.add(nickName + ", 新增成功！");
                    }else {
                        //首先删除原有附件
                        File toDeleteFile = new File(storagePath + "/" + attach.getFileName());
                        if (toDeleteFile.exists()) {
                            toDeleteFile.delete();
                        }
                        System.out.println("attach.getTeacherId ========================================= " + attach.getTeacherId());
                        attach.setFileName(originalFilename);
                        attach.setFilePath(filePath);
                        attach.setFileSize(file.getSize());
                        attach.setFileType(this.getFileExtension(originalFilename));
                        attach.setCreateBy(SecurityUtils.getUsername());
                        attach.setCreateTime(DateUtils.getNowDate());
                        this.attachmentService.updateAttachment(attach);
                        successFiles.add(nickName + ", 覆盖成功！");
                    }
                    //上传文件
                    file.transferTo(new File(savePath));
                }else{
                    failFiles.add(nickName + ", 用户不存在！");
                    //return AjaxResult.error("无此专任教师，上传失败！");
                }
            }
            if(successFiles.size()>0){
                result.put("successFiles", successFiles);
                result.put("successCount", successFiles.size());
            }
            if(failFiles.size()>0) {
                result.put("failFiles", failFiles);
                result.put("failCount", failFiles.size());
            }
            return result;

        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败" + e.getMessage());
        }
    }

    /**
     * 提取文件名中的姓名信息
     * @param fileName
     * @return
     */
    private String extractName(String fileName) {
        // 增强版正则，处理更多边界情况：
        // 1. 可能包含空格
        // 2. 可能没有括号
        // 3. 中英文括号混用
        //Pattern pattern = Pattern.compile("^\\d+\\s*([^（(\\s]+)\\s*[（(]?");
        Pattern pattern = Pattern.compile("^\\d+\\s*([^（(\\s.]+)");
        Matcher matcher = pattern.matcher(fileName);

        return matcher.find() ? matcher.group(1) : "";
    }

    public String getFileExtension(String originalFilename) {
        if (originalFilename == null || originalFilename.isEmpty()) {
            return "";
        }
        String[] parts = originalFilename.split("\\.");
        if (parts.length <= 1) {
            return ""; // 说明没有扩展名或者就是一个点
        }
        return parts[parts.length - 1];
    }

}

